<template>
  <div class="page-container">
    <!-- 顶部标题栏 -->
    <header class="editor-header">
      <el-page-header :content="mode === 'add' ? '添加企业' : '编辑企业'" @back="$router.back()" />
    </header>
    <main class="editor-main">
      <!-- 表单容器1 -->
      <div class="form-container">
        <!-- 表单标题 -->
        <div class="title">企业信息：</div>
        <!-- 企业信息表单 -->
        <div class="form">
          <el-form ref="enterpriseFormRef" :model="enterpriseForm" :rules="enterpriseRules" size="medium" label-width="120px">
            <el-form-item label="企业名称：" prop="name">
              <el-input v-model="enterpriseForm.name" placeholder="请输入企业名称" />
            </el-form-item>
            <el-form-item label="法人：" prop="legalPerson">
              <el-input v-model="enterpriseForm.legalPerson" placeholder="请输入法人" />
            </el-form-item>
            <el-form-item label="注册地址：" prop="registeredAddress">
              <el-input v-model="enterpriseForm.registeredAddress" placeholder="请输入注册地址" />
            </el-form-item>
            <el-form-item label="所在行业：" prop="industryCode">
              <el-select v-model="enterpriseForm.industryCode" placeholder="请选择所在行业">
                <el-option v-for="item in industryList" :key="item.value" :label="item.industryName" :value="item.industryCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="营业执照：" prop="businessLicenseUrl">
              <el-upload
                action="#"
                class="upload-business"
                :limit="1"
                :http-request="uploadRequset"
                :before-upload="beforeUpload"
                list-type="picture"
                :file-list="fileList"
                :on-error="onUplodError"
              >
                <el-button icon="el-icon-upload2" size="medium" type="primary" plain>上传文件</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.png .jpg .jpeg，文件大小不得超过5M</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 表单容器2 -->
      <div class="form-container">
        <!-- 表单标题 -->
        <div class="title">联系人信息：</div>
        <!-- 企业联系人信息表单 -->
        <div class="form">
          <el-form ref="contactFormRef" :model="enterpriseForm" :rules="enterpriseRules" size="medium" label-width="120px">
            <el-form-item label="企业联系人：" prop="contact">
              <el-input v-model="enterpriseForm.contact" placeholder="请输入企业联系人" />
            </el-form-item>
            <el-form-item label="联系电话：" prop="contactNumber">
              <el-input v-model="enterpriseForm.contactNumber" placeholder="请输入联系人电话" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <!-- 底部按钮 -->
    <footer class="editor-footer">
      <div class="btn-container">
        <el-button type="primary" @click="onSave">保存</el-button>
        <el-button class="reset-btn" @click="resetForm">重置</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getIndustryListAPI, addEnterpriseAPI, getEnterpriseDetailsAPI, updateEnterpriseAPI } from '@/api/park/enterprise'
import { uploadAPI } from '@/api/upload'

export default {
  name: 'AddCard',
  data() {
    return {
      // 车辆信息表单数据
      enterpriseForm: {
        name: '', // 企业名称
        legalPerson: '', // 企业法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 行业编号
        businessLicenseUrl: '', // 上传营业执照文件url
        businessLicenseId: '', // 上传营业执照文件id
        contact: '', // 企业联系人
        contactNumber: '' // 企业联系人电话
      },
      // 车辆信息表单验证规则
      enterpriseRules: {
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入企业法人', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '请输入注册地址', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '请选择所在行业', trigger: 'blur' }
        ],
        businessLicenseUrl: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入企业联系人', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      // 行业列表
      industryList: [],
      // 上传文件列表
      fileList: []
    }
  },
  computed: {
    // 编辑模式 add-新增  edit-编辑
    mode() {
      return this.$route.query.mode
    },
    // 当前编辑的企业id
    id() {
      return this.$route.query.id
    }
  },
  created() {
    // 获取行业列表
    this.getIndustryList()
    if (this.mode === 'edit') {
      // 获取当前编辑的企业信息详情
      this.getEnterpriseDetails()
    }
  },
  methods: {
    // 获取行业列表
    async getIndustryList() {
      this.industryList = await getIndustryListAPI()
    },
    // 获取当前编辑的企业信息详情
    async getEnterpriseDetails() {
      this.enterpriseForm = await getEnterpriseDetailsAPI(this.id)
      this.fileList = [{
        id: this.enterpriseForm.businessLicenseId,
        url: this.enterpriseForm.businessLicenseUrl
      }]
    },
    // 上传文件请求
    async uploadRequset(data) {
      const file = data.file

      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'businessLicense')
      const res = await uploadAPI(formData)

      this.enterpriseForm.businessLicenseUrl = res.url
      this.enterpriseForm.businessLicenseId = res.id
    },
    // 编写上传文件校验逻辑
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 上传文件失败
    onUplodError() {
      this.$message.error('上传失败')
    },
    async onSave() {
      // 校验表单
      this.$refs.enterpriseFormRef.validate(async valid => {
        if (valid) {
          this.$refs.contactFormRef.validate(async valid => {
            if (valid) {
              if (this.mode === 'add') {
                // 新增企业
                await addEnterpriseAPI(this.enterpriseForm)
                this.$message.success('新增成功')
              } else {
                // 整理数据
                delete this.enterpriseForm.rent
                delete this.enterpriseForm.businessLicenseName
                delete this.enterpriseForm.industryName

                // 修改企业
                await updateEnterpriseAPI(this.enterpriseForm)
                this.$message.success('修改成功')
              }
              this.$router.push('/park/enterprise')
            }
          })
        }
      })
    },
    // 重置表单
    resetForm() {
      this.enterpriseForm = {
        name: '', // 企业名称
        legalPerson: '', // 企业法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 行业编号
        businessLicenseUrl: '', // 上传营业执照文件url
        businessLicenseId: '', // 上传营业执照文件id
        contact: '', // 企业联系人
        contactNumber: '' // 企业联系人电话
      }
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {
  .editor-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    margin-bottom: 30px;
    height: 64px;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    ::v-deep .el-page-header {
      .el-page-header__title {
        font-size: 16px;
        font-weight: 600;
        color: #444;
      }

      .el-page-header__content {
        font-size: 16px;
        font-weight: 600;
        color: #444;
      }
    }
  }

  .editor-main {
    padding-left: 50px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
        font-weight: 600;
        color: #444;
      }

      .form {
        padding: 20px 65px 10px;

        .el-input, .el-select, .upload-business {
          width: 400px;
        }
      }
    }
    .preview{
      img{
        width: 100px;
      }
    }
  }

  .editor-footer {
    width: 100%;
    padding: 20px 0 20px 280px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;

    .reset-btn {
      margin-left: 30px;
    }
  }
}
</style>
